/* 结算页面逻辑 */
class CheckoutManager {
    constructor() {
        this.orderItems = [];
        this.selectedAddress = null;
        this.shippingMethod = 'standard';
        this.paymentMethod = 'alipay';
        this.currentDiscount = 0;
        this.shippingFee = 15.00;
        this.addresses = [];
        this.init();
    }

    init() {
        this.getDiscountFromURL();
        this.bindEvents();
        this.loadOrderData();
        this.loadAddresses();
    }

    getDiscountFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        const discount = urlParams.get('discount');
        if (discount) {
            this.currentDiscount = parseFloat(discount);
        }
    }

    bindEvents() {
        // 地址相关
        document.getElementById('addAddressBtn').addEventListener('click', this.showAddressForm.bind(this));
        document.getElementById('cancelAddressForm').addEventListener('click', this.hideAddressForm.bind(this));
        document.getElementById('newAddressForm').addEventListener('submit', this.saveAddress.bind(this));

        // 配送方式
        document.querySelectorAll('.shipping-option').forEach(option => {
            option.addEventListener('click', (e) => {
                this.selectShippingMethod(e.currentTarget.dataset.shipping);
            });
        });

        // 支付方式
        document.querySelectorAll('.payment-option').forEach(option => {
            option.addEventListener('click', (e) => {
                this.selectPaymentMethod(e.currentTarget.dataset.payment);
            });
        });

        // 提交订单
        document.getElementById('submitOrderBtn').addEventListener('click', this.submitOrder.bind(this));

        // 玩折扣游戏
        document.getElementById('playGameBtn').addEventListener('click', this.playDiscountGame.bind(this));

        // 订单成功模态框
        document.getElementById('viewOrderBtn').addEventListener('click', this.viewOrder.bind(this));
        document.getElementById('continueShoppingBtn').addEventListener('click', this.continueShopping.bind(this));
    }

    loadOrderData() {
        // 等待cartManager初始化完成
        if (window.cartManager) {
            this.loadCartData();
        } else {
            // 如果cartManager还没加载，延迟重试
            setTimeout(() => {
                this.loadOrderData();
            }, 100);
        }
    }
    
    loadCartData() {
        try {
            // 首先尝试从localStorage获取结算商品
            const checkoutItems = localStorage.getItem('checkoutItems');
            if (checkoutItems) {
                this.orderItems = JSON.parse(checkoutItems);
                console.log('从localStorage加载结算商品:', this.orderItems);
                this.renderOrderItems();
                this.updateSummary();
                return;
            }
            
            // 如果没有localStorage数据，尝试从cartManager获取
            if (window.cartManager) {
                const cartData = window.cartManager.getCartData();
                this.orderItems = cartData.selectedItems;
                
                console.log('购物车数据:', cartData);
                console.log('选中的商品:', this.orderItems);
            }
            
            if (this.orderItems.length === 0) {
                // 尝试从URL参数获取商品信息（直接购买）
                this.loadFromURLParams();
                if (this.orderItems.length === 0) {
                    this.showNotification('购物车为空，请先选择商品', 'error');
                    setTimeout(() => {
                        window.location.href = 'cart.html';
                    }, 2000);
                    return;
                }
            }
            
            this.renderOrderItems();
            this.updateSummary();
        } catch (error) {
            console.error('加载购物车数据失败:', error);
            this.showNotification('加载购物车数据失败', 'error');
        }
    }
    
    loadFromURLParams() {
        // 从URL参数加载商品信息（直接购买场景）
        const urlParams = new URLSearchParams(window.location.search);
        const productId = urlParams.get('productId');
        const quantity = parseInt(urlParams.get('quantity')) || 1;
        
        if (productId) {
            // 这里需要从后端获取商品信息
            this.loadProductFromAPI(productId, quantity);
        }
    }
    
    async loadProductFromAPI(productId, quantity) {
        try {
            if (window.api) {
                const result = await window.api.getProduct(productId);
                if (result.success) {
                    const product = result.data;
                    this.orderItems = [{
                        product_id: product.id,
                        product_name: product.name,
                        price: product.price,
                        quantity: quantity,
                        selected: true,
                        image: product.image,
                        category: product.category
                    }];
                    console.log('从API加载商品:', this.orderItems);
                }
            }
        } catch (error) {
            console.error('从API加载商品失败:', error);
        }
    }

    renderOrderItems() {
        const orderItemsContainer = document.getElementById('orderItems');
        
        orderItemsContainer.innerHTML = this.orderItems.map(item => `
            <div class="order-item">
                <div class="item-image">
                    <img src="https://via.placeholder.com/80x80?text=${encodeURIComponent(item.product_name)}" 
                         alt="${item.product_name}"
                         onerror="this.src='https://via.placeholder.com/80x80?text=商品图片'">
                </div>
                <div class="item-info">
                    <h3 class="item-name">${item.product_name}</h3>
                    <div class="item-specs">
                        <span class="spec">数量: ${item.quantity}</span>
                        <span class="spec">单价: ¥${item.price.toFixed(2)}</span>
                    </div>
                </div>
                <div class="item-total">
                    <span class="total-price">¥${(item.price * item.quantity).toFixed(2)}</span>
                </div>
            </div>
        `).join('');
    }

    loadAddresses() {
        // 模拟地址数据
        this.addresses = [
            {
                id: 1,
                name: '张三',
                phone: '13800138000',
                address: '北京市朝阳区三里屯街道工体北路8号院',
                isDefault: true
            },
            {
                id: 2,
                name: '李四',
                phone: '13900139000',
                address: '上海市浦东新区陆家嘴金融贸易区世纪大道100号',
                isDefault: false
            }
        ];

        this.renderAddresses();
    }

    renderAddresses() {
        const addressList = document.getElementById('addressList');
        
        addressList.innerHTML = this.addresses.map(address => `
            <div class="address-item ${address.isDefault ? 'default' : ''}" data-address-id="${address.id}">
                <div class="address-content">
                    <div class="address-header">
                        <span class="recipient-name">${address.name}</span>
                        <span class="recipient-phone">${address.phone}</span>
                        ${address.isDefault ? '<span class="default-badge">默认</span>' : ''}
                    </div>
                    <div class="address-detail">${address.address}</div>
                </div>
                <div class="address-actions">
                    <button class="btn btn-outline btn-sm select-address" data-address-id="${address.id}">
                        ${address.isDefault ? '已选择' : '选择'}
                    </button>
                    <button class="btn btn-outline btn-sm edit-address" data-address-id="${address.id}">编辑</button>
                    <button class="btn btn-outline btn-sm delete-address" data-address-id="${address.id}">删除</button>
                </div>
            </div>
        `).join('');

        // 绑定地址操作事件
        this.bindAddressEvents();
        
        // 默认选择第一个地址
        if (this.addresses.length > 0) {
            this.selectAddress(this.addresses[0].id);
        }
    }

    bindAddressEvents() {
        // 选择地址
        document.querySelectorAll('.select-address').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const addressId = parseInt(e.target.dataset.addressId);
                this.selectAddress(addressId);
            });
        });

        // 编辑地址
        document.querySelectorAll('.edit-address').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const addressId = parseInt(e.target.dataset.addressId);
                this.editAddress(addressId);
            });
        });

        // 删除地址
        document.querySelectorAll('.delete-address').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const addressId = parseInt(e.target.dataset.addressId);
                this.deleteAddress(addressId);
            });
        });
    }

    selectAddress(addressId) {
        // 更新选中状态
        document.querySelectorAll('.address-item').forEach(item => {
            item.classList.remove('selected');
        });
        
        const selectedItem = document.querySelector(`[data-address-id="${addressId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('selected');
        }

        // 更新按钮状态
        document.querySelectorAll('.select-address').forEach(btn => {
            btn.textContent = '选择';
            btn.classList.remove('btn-primary');
            btn.classList.add('btn-outline');
        });
        
        const selectedBtn = document.querySelector(`.select-address[data-address-id="${addressId}"]`);
        if (selectedBtn) {
            selectedBtn.textContent = '已选择';
            selectedBtn.classList.remove('btn-outline');
            selectedBtn.classList.add('btn-primary');
        }

        this.selectedAddress = this.addresses.find(addr => addr.id === addressId);
    }

    showAddressForm() {
        document.getElementById('addressForm').style.display = 'block';
        document.getElementById('addAddressBtn').style.display = 'none';
    }

    hideAddressForm() {
        document.getElementById('addressForm').style.display = 'none';
        document.getElementById('addAddressBtn').style.display = 'block';
        document.getElementById('newAddressForm').reset();
    }

    saveAddress(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const newAddress = {
            id: Date.now(),
            name: formData.get('recipientName'),
            phone: formData.get('recipientPhone'),
            address: formData.get('address'),
            isDefault: this.addresses.length === 0
        };

        this.addresses.push(newAddress);
        this.renderAddresses();
        this.hideAddressForm();
        this.showNotification('地址保存成功', 'success');
    }

    editAddress(addressId) {
        const address = this.addresses.find(addr => addr.id === addressId);
        if (!address) return;

        // 填充表单
        document.getElementById('recipientName').value = address.name;
        document.getElementById('recipientPhone').value = address.phone;
        document.getElementById('address').value = address.address;

        this.showAddressForm();
        
        // 修改表单提交行为
        const form = document.getElementById('newAddressForm');
        form.onsubmit = (e) => {
            e.preventDefault();
            this.updateAddress(addressId, e.target);
        };
    }

    updateAddress(addressId, form) {
        const formData = new FormData(form);
        const address = this.addresses.find(addr => addr.id === addressId);
        
        if (address) {
            address.name = formData.get('recipientName');
            address.phone = formData.get('recipientPhone');
            address.address = formData.get('address');
            
            this.renderAddresses();
            this.hideAddressForm();
            this.showNotification('地址更新成功', 'success');
        }
    }

    deleteAddress(addressId) {
        if (confirm('确定要删除这个地址吗？')) {
            this.addresses = this.addresses.filter(addr => addr.id !== addressId);
            this.renderAddresses();
            this.showNotification('地址删除成功', 'success');
        }
    }

    selectShippingMethod(method) {
        this.shippingMethod = method;
        
        // 更新UI
        document.querySelectorAll('.shipping-option').forEach(option => {
            option.classList.remove('active');
        });
        document.querySelector(`[data-shipping="${method}"]`).classList.add('active');
        
        // 更新运费
        this.shippingFee = method === 'express' ? 25.00 : 15.00;
        this.updateSummary();
    }

    selectPaymentMethod(method) {
        this.paymentMethod = method;
        
        // 更新UI
        document.querySelectorAll('.payment-option').forEach(option => {
            option.classList.remove('active');
        });
        document.querySelector(`[data-payment="${method}"]`).classList.add('active');
    }

    updateSummary() {
        const subtotal = this.orderItems.reduce((total, item) => total + (item.price * item.quantity), 0);
        const discountAmount = subtotal * this.currentDiscount / 100;
        const totalAmount = subtotal + this.shippingFee - discountAmount;

        // 更新UI
        document.getElementById('subtotal').textContent = `¥${subtotal.toFixed(2)}`;
        document.getElementById('shippingFee').textContent = `¥${this.shippingFee.toFixed(2)}`;
        document.getElementById('totalAmount').textContent = `¥${totalAmount.toFixed(2)}`;

        // 显示折扣信息
        const discountItem = document.getElementById('discountItem');
        if (this.currentDiscount > 0) {
            discountItem.style.display = 'flex';
            discountItem.querySelector('.discount-amount').textContent = `-¥${discountAmount.toFixed(2)}`;
        } else {
            discountItem.style.display = 'none';
        }
    }

    playDiscountGame() {
        if (window.discountGame) {
            window.discountGame.showGameModal();
        }
    }

    applyDiscount(discountPercent) {
        this.currentDiscount = discountPercent;
        this.updateSummary();
        this.showNotification(`成功获得 ${discountPercent}% 折扣！`, 'success');
    }

    async submitOrder() {
        // 验证必填信息
        if (!this.selectedAddress) {
            this.showNotification('请选择收货地址', 'error');
            return;
        }

        if (this.orderItems.length === 0) {
            this.showNotification('购物车为空', 'error');
            return;
        }

        try {
            this.showLoading(true);

            // 构建订单数据
            const orderData = {
                items: this.orderItems.map(item => ({
                    productId: item.product_id,
                    product_name: item.product_name,
                    price: item.price,
                    quantity: item.quantity
                })),
                shippingAddress: {
                    name: this.selectedAddress.name,
                    phone: this.selectedAddress.phone,
                    address: this.selectedAddress.address
                },
                paymentMethod: this.paymentMethod,
                discount: this.currentDiscount
            };

            // 模拟API调用
            const result = await this.createOrder(orderData);
            
            if (result.success) {
                this.showOrderSuccess(result.data);
                
                // 清空购物车中的已下单商品
                if (window.cartManager) {
                    this.orderItems.forEach(item => {
                        window.cartManager.removeFromCart(item.product_id);
                    });
                }
            } else {
                this.showNotification(result.error || '订单提交失败', 'error');
            }

        } catch (error) {
            console.error('提交订单失败:', error);
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    async createOrder(orderData) {
        try {
            console.log('开始创建订单:', orderData);
            
            // 调用真实的后端API
            const result = await window.api.createOrder(orderData);
            
            console.log('订单创建结果:', result);
            
            if (result.success) {
                // 返回与后端API一致的格式
                return {
                    success: true,
                    data: {
                        orderNumber: result.data.order_number,
                        estimatedDelivery: new Date(result.data.estimated_delivery * 1000).toISOString().split('T')[0],
                        totalAmount: result.data.total_amount,
                        status: result.data.status
                    }
                };
            } else {
                return {
                    success: false,
                    error: result.error
                };
            }
        } catch (error) {
            console.error('创建订单API调用失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    calculateTotalAmount() {
        const subtotal = this.orderItems.reduce((total, item) => total + (item.price * item.quantity), 0);
        const discountAmount = subtotal * this.currentDiscount / 100;
        return subtotal + this.shippingFee - discountAmount;
    }

    showOrderSuccess(orderData) {
        const modal = document.getElementById('orderSuccessModal');
        document.getElementById('orderNumber').textContent = orderData.orderNumber;
        document.getElementById('estimatedDelivery').textContent = orderData.estimatedDelivery;
        
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    viewOrder() {
        // 跳转到订单详情页
        window.location.href = 'orders.html';
    }

    continueShopping() {
        // 跳转到首页
        window.location.href = 'index.html';
    }

    showLoading(show) {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.style.display = show ? 'flex' : 'none';
        }
    }

    showNotification(message, type = 'info') {
        if (window.authManager && window.authManager.showNotification) {
            window.authManager.showNotification(message, type);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 延迟初始化，确保所有模块都已加载
    setTimeout(() => {
        window.checkoutManager = new CheckoutManager();
        
        // 监听折扣游戏结果
        if (window.discountGame) {
            // 重写折扣游戏的applyDiscount方法
            const originalApplyDiscount = window.discountGame.applyDiscount;
            window.discountGame.applyDiscount = function(discountPercent) {
                originalApplyDiscount.call(this, discountPercent);
                if (window.checkoutManager) {
                    window.checkoutManager.applyDiscount(discountPercent);
                }
            };
        }
    }, 200);
});
